<template>
  <div id="app">
    <Navbar />
    <div class="shopping-cart">
      <div class="left-panel">
        <h2>总计</h2>
        <ul class="left-list">
          <li v-for="(item, index) in selectedProducts" :key="index">
            {{ item.quantity > 1 ? `${item.name} x${item.quantity}` : item.name }}
          </li>
        </ul>
        <button class="total-button" @click="checkout">结算</button>
        <span class="total-price">¥{{ totalPrice }}</span>
        <button class="delete-selected-button" @click="deleteSelectedProducts" :disabled="!hasSelectedProducts">
          删除选中商品
        </button>
      </div>
      <div class="right-panel">
        <div class="filter-search">
          <button class="all-button" @click="selectAllProducts">all</button>
          <input type="text" placeholder="search" class="search-input" v-model="searchKeyword" />
          <button class="search-icon">
            <i class="fas fa-search">🔍</i>
          </button>
        </div>
        <div class="product-list">
          <!-- 确保使用过滤后的产品列表 -->
          <div 
            v-for="(product, index) in filteredProducts" 
            :key="product.id"
            class="product-item"
            :class="{ 'out-of-stock': product.stock_quantity <= 0 }"
          >
            <input 
              type="checkbox" 
              v-model="product.isChecked" 
              @change="calculateTotal"
              :disabled="product.stock_quantity <= 0"
            />
            <img :src="product.image_url" alt="product" class="product-image" />
            <div class="product-info">
              <span class="product-name">{{ product.name }}</span>
              <span class="product-price">¥{{ product.price * product.quantity }}</span>
              <input 
                type="number" 
                v-model.number="product.quantity" 
                @input="calculateTotal" 
                min="1"
                class="quantity-input"
                :disabled="product.stock_quantity <= 0"
              />
              <button class="delete-button" @click="deleteSingleProduct(index)">
                delete
              </button>
              <button class="favorite-button" @click="toggleFavorite(product)">
                {{ isFavorited(product) ? '★ 已收藏' : '☆ 收藏' }}
              </button>
              <span class="stock-status" v-if="product.stock_quantity <= 0">无库存</span>
            </div>
          </div>
          <!-- 当没有搜索结果时显示提示信息 -->
          <div v-if="!filteredProducts.length && searchKeyword" class="no-results">
            没有找到匹配 "{{ searchKeyword }}" 的商品
          </div>
        </div>
      </div>
    </div>

    <footer class="footer-links">
      <div class="link-group">
        <a>关于校麦</a>
        <a>协议及隐私权政策</a>
        <a>廉正举报</a>
        <a>联系合作</a>
      </div>
      <div class="link-group">
        <a>招聘信息</a>
        <a>防骗秘籍</a>
        <a>商户入驻</a>
      </div>
      <div class="copyright">© 2025-2025 校麦网</div>
    </footer>

    <LoginDialog v-if="showLoginDialog" @close="showLoginDialog = false" />
    <RegisterDialog v-if="showRegisterDialog" @close="showRegisterDialog = false" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import { useRouter } from "vue-router";
import LoginDialog from "../../components/LoginDialog.vue";
import RegisterDialog from "../../components/RegisterDialog.vue";
import Navbar from "../../components/Navbar.vue";
import axios from "axios";
import { ElMessage } from 'element-plus';

const API_URL = "http://localhost:3000"; // json-server 地址

// 定义响应式数据
const showLoginDialog = ref(false);
const showRegisterDialog = ref(false);
const isLoggedIn = ref(localStorage.getItem("isLoggedIn") === "true");
const router = useRouter();
const currentUser = ref(localStorage.getItem("currentUser") || "b88a"); // 默认用户ID，需根据登录逻辑修改
const products = ref([]); // 购物车商品
const favorites = ref([]); // 收藏数据
const totalPrice = ref(0);
const isSticky = ref(false);
const searchKeyword = ref("");

// 提取卖家ID的辅助函数
const extractSellerId = (product) => {
  try {
    // 检查userId是否存在
    if (!product.userId) {
      console.warn("商品缺少userId属性:", product);
      return null;
    }
    
    // 尝试解析userId
    if (typeof product.userId === 'string') {
      try {
        const userData = JSON.parse(product.userId);
        return userData.id || null;
      } catch (error) {
        console.error("解析userId失败:", error);
        // 如果解析失败，直接返回userId作为sellerId
        return product.userId;
      }
    }
    
    // 如果userId已经是对象
    if (typeof product.userId === 'object' && product.userId !== null) {
      return product.userId.id || null;
    }
    
    return null;
  } catch (error) {
    console.error("提取卖家ID失败:", error);
    return null;
  }
};

// 获取卖家信息
const getSellerInfo = async (sellerId) => {
  try {
    // 尝试从sellers表获取卖家信息
    const sellerResponse = await axios.get(`${API_URL}/sellers/${sellerId}`);
    return sellerResponse.data;
  } catch (error) {
    console.warn("获取卖家详细信息失败，使用默认信息:", error);
    // 如果无法获取卖家详细信息，返回默认信息
    return {
      id: sellerId,
      name: `卖家${sellerId}`,
      shopName: `店铺${sellerId}`
    };
  }
};

// 退出登录
const logout = () => {
  localStorage.removeItem("isLoggedIn");
  localStorage.removeItem("currentUser");
  isLoggedIn.value = false;
  currentUser.value = "";
};

// 从服务器获取购物车数据
const fetchCartData = async () => {
  try {
    // 获取当前用户的购物车
    const cartResponse = await axios.get(`${API_URL}/carts?userId=${encodeURIComponent(currentUser.value)}`);
    const cart = cartResponse.data[0] || { items: [] };
    
    // 获取所有商品信息（用于补充库存等信息）
    const productsResponse = await axios.get(`${API_URL}/products`);
    const allProducts = productsResponse.data;
    
    // 合并购物车数据和商品信息
    const mergedProducts = cart.items.map(cartItem => {
      const productInfo = allProducts.find(p => p.id === cartItem.productId) || {};
      return {
        ...cartItem,
        ...productInfo, // 合并商品信息（如库存、图片等）
        stock_quantity: productInfo.stock_quantity || 0
      };
    });
    
    products.value = mergedProducts;
    calculateTotal();
  } catch (error) {
    console.error("获取购物车数据失败:", error);
    ElMessage.error("加载购物车失败，请稍后重试");
  }
};

// 从服务器获取收藏数据
const fetchFavorites = async () => {
  try {
    const favoritesResponse = await axios.get(`${API_URL}/favorites?userId=${encodeURIComponent(currentUser.value)}`);
    favorites.value = favoritesResponse.data;
  } catch (error) {
    console.error("获取收藏数据失败:", error);
    ElMessage.error("加载收藏数据失败，请稍后重试");
  }
};

// 计算属性：过滤商品
const filteredProducts = computed(() => {
  if (!searchKeyword.value) {
    return products.value;
  }
  return products.value.filter((product) =>
    product.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 计算属性：获取选中的商品并合并相同商品
const selectedProducts = computed(() => {
  return products.value
    .filter((product) => product.isChecked && product.stock_quantity > 0)
    .reduce((merged, product) => {
      const existingProduct = merged.find((p) => p.id === product.id);
      if (existingProduct) {
        existingProduct.quantity += product.quantity;
      } else {
        merged.push({ ...product, quantity: product.quantity });
      }
      return merged;
    }, []);
});

// 计算属性：判断是否有选中的商品
const hasSelectedProducts = computed(() => {
  return selectedProducts.value.length > 0;
});

// 滚动事件处理函数
const handleScroll = () => {
  if (window.pageYOffset > 0) {
    isSticky.value = true;
  } else {
    isSticky.value = false;
  }
};

// 计算总价函数
const calculateTotal = () => {
  totalPrice.value = selectedProducts.value.reduce(
    (sum, product) => sum + product.price * product.quantity,
    0
  );
};

// 删除单个商品函数
const deleteSingleProduct = async (index) => {
  try {
    const productToDelete = products.value[index];
    
    // 获取当前用户的购物车
    const cartResponse = await axios.get(`${API_URL}/carts?userId=${encodeURIComponent(currentUser.value)}`);
    const cart = cartResponse.data[0];
    
    // 更新购物车（移除商品）
    cart.items = cart.items.filter(item => item.productId !== productToDelete.id);
    
    // 保存到服务器
    await axios.patch(`${API_URL}/carts/${cart.id}`, cart);
    
    // 更新本地状态
    products.value.splice(index, 1);
    calculateTotal();
    ElMessage.success("商品已删除");
  } catch (error) {
    console.error("删除商品失败:", error);
    ElMessage.error("删除商品失败，请稍后重试");
  }
};

// 删除选中商品函数
const deleteSelectedProducts = async () => {
  try {
    if (!hasSelectedProducts.value) {
      ElMessage.warning("请先选择要删除的商品");
      return;
    }
    
    // 获取当前用户的购物车
    const cartResponse = await axios.get(`${API_URL}/carts?userId=${encodeURIComponent(currentUser.value)}`);
    const cart = cartResponse.data[0];
    
    // 过滤掉选中的商品
    const selectedIds = selectedProducts.value.map(p => p.id);
    cart.items = cart.items.filter(item => !selectedIds.includes(item.productId));
    
    // 保存到服务器
    await axios.patch(`${API_URL}/carts/${cart.id}`, cart);
    
    // 更新本地状态
    products.value = products.value.filter(product => !product.isChecked);
    calculateTotal();
    ElMessage.success("已删除选中商品");
  } catch (error) {
    console.error("删除选中商品失败:", error);
    ElMessage.error("删除商品失败，请稍后重试");
  }
};

// 全选商品函数
const selectAllProducts = () => {
  const hasInStockProducts = filteredProducts.value.some(
    (product) => product.stock_quantity > 0
  );
  
  if (!hasInStockProducts) return;
  
  const allInStockChecked = filteredProducts.value
    .filter(p => p.stock_quantity > 0)
    .every((product) => product.isChecked);
  
  filteredProducts.value.forEach((product) => {
    if (product.stock_quantity > 0) {
      product.isChecked = !allInStockChecked;
    }
  });
  
  calculateTotal();
};

// 结算函数
const checkout = async () => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true;
    return;
  }

  if (!hasSelectedProducts.value) {
    ElMessage.warning("请选择有库存的商品");
    return;
  }

  try {
    // 1. 批量校验并更新库存
    await Promise.all(
      selectedProducts.value.map(async (product) => {
        const productId = product.id;
        const deductQuantity = product.quantity;

        // 获取当前库存
        const stockRes = await axios.get(`${API_URL}/products/${productId}`);
        const currentStock = stockRes.data.stock_quantity;
        
        // 校验库存
        if (currentStock < deductQuantity) {
          throw new Error(`【${product.name}】库存不足（剩余 ${currentStock} 件，需购买 ${deductQuantity} 件）`);
        }

        // 更新库存
        await axios.patch(`${API_URL}/products/${productId}`, {
          stock_quantity: currentStock - deductQuantity
        });
      })
    );

    // 2. 创建订单并保存到数据库
    // 从第一个商品中提取卖家ID
    const firstProduct = selectedProducts.value[0];
    const sellerId = extractSellerId(firstProduct) || `MERCH${firstProduct.shopName || firstProduct.id}`;
    
    // 获取卖家信息
    const sellerInfo = await getSellerInfo(sellerId);
    
    // 构建订单数据
    const orderData = {
      userId: currentUser.value,
      merchantid: sellerInfo.id,
      products: selectedProducts.value.map(product => ({
        productId: product.id,
        name: product.name,
        price: product.price,
        quantity: product.quantity,
        image_url: product.image_url,
        shopName: product.shopName,
      })),
      totalPrice: totalPrice.value,
      status: "待接单",
      createdAt: new Date().toISOString(),
    };

    console.log('创建订单:', orderData);

    // 发送订单数据到后端保存
    const orderResponse = await axios.post(`${API_URL}/orders`, orderData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('订单已保存到数据库:', orderResponse.data);

    // 3. 清空购物车选中商品
    deleteSelectedProducts();

    ElMessage.success("结算成功！订单已创建");
    router.push('/main/profile/user-center/orders');
  } catch (error) {
    console.error("结算失败:", error);
    
    // 提供更详细的错误信息
    if (error.response) {
      // 请求已发送，服务器响应了状态码
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.data.message || '保存订单失败'}`);
    } else if (error.request) {
      // 请求已发送，但没有收到响应
      ElMessage.error("服务器未响应，请检查API服务是否正常运行");
    } else {
      // 发生了其他错误
      ElMessage.error(error.message || "结算过程中发生错误");
    }
  }
};

// 收藏相关逻辑
const isFavorited = (product) => {
  return favorites.value.some(fav => fav.productId === product.id && fav.userId === currentUser.value);
};

const toggleFavorite = async (product) => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true;
    return;
  }

  const productId = product.id;
  const productData = { ...product }; // 保存完整商品信息

  try {
    // 检查当前商品是否已被收藏
    const existingFavorite = favorites.value.find(
      fav => fav.productId === productId && fav.userId === currentUser.value
    );

    if (existingFavorite) {
      // 已收藏：删除收藏记录
      await axios.delete(`${API_URL}/favorites/${existingFavorite.id}`);
      ElMessage.success("已取消收藏");
    } else {
      // 未收藏：添加收藏记录
      const newFavorite = {
        userId: currentUser.value,
        productId,
        product: productData, // 存储完整商品信息
        createdAt: new Date().toISOString()
      };
      await axios.post(`${API_URL}/favorites`, newFavorite);
      ElMessage.success("收藏成功！");
    }

    // 更新页面状态
    fetchFavorites(); // 重新获取收藏数据
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

// 挂载时绑定滚动事件并加载数据
onMounted(() => {
  window.addEventListener("scroll", handleScroll);
  fetchCartData();
  fetchFavorites();
});

// 卸载前移除滚动事件
onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
#app {
  width: 100vw;
  height: auto;
  margin: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  padding: 0rem;
  text-align: center;
  color: #ffffff;
}
h2{
  color: #333;
}
.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #E05649;
  padding: 10px 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.nav-link:hover {
  color: rgb(130, 69, 25);
  /* background-color: #333; */
  border-radius: 20%;
}

.nav-link {
  margin-right: 20px;
  text-decoration: none;
  color: rgb(255, 255, 255);
}

.sign-in-button,
.register-button,
.sign-out-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

.shopping-cart {
  margin-top: 50px;
  display: flex;
  width: 100%;
  height: auto;
  background-color: #efefef;
  min-height: 500px;
}

.left-panel {
  width: 240px;
  padding: 20px 0;
  border-right: 1px solid #eee;
  background-color: #ffffff;
  position: fixed;
  top: 60px;
  bottom: 0;
  left: 20px;
  overflow-y: auto;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}
.total-a{
  color: #ffffff;
}
.total-price{
  color: #333;
}
.right-panel {
  flex: 1;
  padding: 20px;
  margin-left: 350px;
  max-width: 1200px;
  margin-right: auto;
  margin-top: -20px;
  display: flex;
  flex-direction: column;
}

.filter-search {
  display: flex;
  align-self: center;
  margin-bottom: 20px;
  margin-top: 20px;
  width: 30rem;
}

.all-button {
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #e05649;
  color: white;
  border: none;
  cursor: pointer;
}

.search-input {
  flex: 1;
  padding: 5px;
  border-radius: 5px;
}

.search-icon {
  padding: 5px 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  cursor: pointer;
}

.product-list {
  display: flex;
  flex-direction: column;
}

.product-item {
  width: calc(90% - 20px);
  margin-bottom: 20px;
  border: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  border-radius: 10px;
  align-items: center;
  background-color: #ffffff;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 10px;
}

.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  margin-left: 10px;
  color: #333;
}

.delete-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

.total-button {
  width: 100%;
  padding: 10px;
  background-color: #e05649;
  color: white;
  border: none;
  cursor: pointer;
  margin-top: 20px;
}

.delete-selected-button {
  width: 100%;
  padding: 10px;
  background-color: #333;
  color: white;
  border: none;
  cursor: pointer;
  margin-top: 20px;
  opacity: 0.5;
  pointer-events: none;
}

.delete-selected-button:enabled {
  opacity: 1;
  pointer-events: auto;
}

.left-list {
  list-style: none;
  margin-right: 40px;
  color: #333;
}

.quantity-input {
  width: 50px;
  padding: 5px;
  margin-left: 10px;
}

.favorite-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  margin-left: 10px;
  border-radius: 5px;
}

.favorite-button:hover {
  opacity: 0.8;
}
.footer-links {
  border-top: 1px solid #eee;
  padding: 30px;
  text-align: center;
  margin-left: 260px;
  /* 向右移动，与左侧导航栏对齐 */
}

.link-group {
  margin-bottom: 12px;
}

.link-group a {
  color: #999;
  font-size: 12px;
  margin: 0 12px;
  cursor: pointer;
}

.link-group a:hover {
  color: #230303;
}

.copyright {
  color: #ccc;
  font-size: 12px;
  margin-top: 20px;
}

.out-of-stock {
  background-color: #f8f8f8;
  opacity: 0.7;
  position: relative;
}

.out-of-stock .product-name,
.out-of-stock .product-price {
  color: #999;
}

.out-of-stock input:disabled,
.out-of-stock button:disabled {
  cursor: not-allowed;
}

.stock-status {
  color: #e05649;
  font-weight: bold;
  margin-left: 10px;
}
</style>